package cn.com.jsepc.rep.comm;

import java.sql.*;

import com.jarp.db.ConnectionPools;


public class DBConnect {
	private static DBConnect instance = null;

	public static synchronized DBConnect getInstance() {
		if (instance == null) {
			instance = new DBConnect();
		}
		return instance;
	}
	
	public DBConnect() {
	}

	public static Connection getConnection() throws SQLException {
		Connection conn = null;
		try {
//				Class.forName("com.ibm.db2.jcc.DB2Driver").newInstance();
//				String url = "jdbc:db2://172.23.30.12:50007/JHTJ2";
//				String user = "db2inst1";
//				String password = "db2inst1";
//				conn = DriverManager.getConnection(url, user, password);
			conn = ConnectionPools.getInstance().getConnection(ConstUtil.DBNAME);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return conn;
	}
	
	public static void retConnectionODS() throws SQLException {
		ConnectionPools.getInstance().returnConnection(ConstUtil.DBNAMEODS);
	}
	
	public static Connection getODSConnection() throws SQLException {
		Connection conn = null;
		try {
			conn = ConnectionPools.getInstance().getConnection(ConstUtil.DBNAMEODS);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return conn;
	}
	
	public static void retConnection() throws SQLException {
		ConnectionPools.getInstance().returnConnection(ConstUtil.DBNAME);
	}
	
	public String getSequence(String seqName){
		
		String seqValue = "";
		PreparedStatement stmt = null;
		ResultSet rs = null;
		Connection conn = ConnectionPools.getInstance().getConnection("Jarp");
		try{
			String sqlStmt = null;
			if (ConstUtil.DBTYPE.equals("DB2")){
				sqlStmt = "values nextval for "+seqName ;
			}else if (ConstUtil.DBTYPE.equals("ORACLE")){
				sqlStmt = "select "+seqName+".nextval from dual" ;
			}
			
			 if (conn != null){
				 stmt = conn.prepareStatement(sqlStmt);
				 rs = stmt.executeQuery();
				 if (rs.next()) {
				 	seqValue = String.valueOf(rs.getInt(1));
				 }
			 }
//			 System.out.println("\n--getSequence seqValue :"+seqValue);		
		}catch (Exception ex) {
			ex.printStackTrace();
		}finally{
			try {
				if (rs !=null ) rs.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
			try {
				if (stmt !=null ) stmt.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
			ConnectionPools.getInstance().returnConnection("Jarp");
		}
		return seqValue;
	}
	
}
